#include "cpurankitemdelegate.h"
#include "cpurankitem.h"
#include "cpurankviewmodel.h"

#include <QEvent>
#include <QImage>
#include <QMouseEvent>
#include <QPainter>
#include <QRegion>

CpuRankItemDelegate::CpuRankItemDelegate(QObject *parent)
    : QAbstractItemDelegate{parent}
{
    if (m_itemWidget.isNull()) {
        m_itemWidget.reset(new CpuRankItem);
        m_itemWidget->setVisible(false);
    }
}

void CpuRankItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    CpuRankItem::fromMap(index.data(CpuRankViewModel::CpuRankData).toMap(), m_itemWidget.data())
        ->setSwtiched(index.data(CpuRankViewModel::CpuRankExtSwitched).toBool());

    m_itemWidget->resize(option.rect.size());


//  [1] 第一种方式
//    qreal dpr = painter->device()->devicePixelRatioF();
//    QPixmap pixmap(option.rect.size() * dpr);
//    pixmap.setDevicePixelRatio(dpr);
//    pixmap.fill(Qt::transparent);

//    m_itemWidget->render(&pixmap, QPoint(),
//                         // QRegion(QRect(QPoint(), option.rect.size() * dpr)),
//                         QRect(QPoint(), option.rect.size() * dpr),
//                         QWidget::DrawChildren);

//  [2] 第二种方式
    QPixmap pixmap = m_itemWidget->grab();

    // 开始绘制
    painter->save();
    painter->drawPixmap(option.rect, pixmap); // [1]高分屏炸(所以使用了 dpr 处理 pixmap), [2]这个直接解决问题
    painter->restore();
}

QSize CpuRankItemDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    if (m_itemWidget.isNull()) {
        return QSize();
    }
    return m_itemWidget->sizeHint();
}

bool CpuRankItemDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index)
{
    static QPoint onePos;

    bool rpaint = false;
    if (event->type() == QEvent::MouseButtonPress) {
        auto mouse_event = static_cast<QMouseEvent*>(event);
        if (option.rect.contains(mouse_event->pos())) {
            onePos = mouse_event->pos();
        }
    }
    if (event->type() == QEvent::MouseButtonRelease) {
        auto mouse_event = static_cast<QMouseEvent*>(event);
        if (option.rect.contains(mouse_event->pos())) {
            if (onePos == mouse_event->pos()) {
                auto switched = model->data(index, CpuRankViewModel::CpuRankExtSwitched).toBool();
                model->setData(index, !switched, CpuRankViewModel::CpuRankExtSwitched);
                rpaint = true;

                auto id = model->data(index, CpuRankViewModel::CpuRankId).toString();
                emit switchIdChagned(id, !switched);
            }
        }
    }

    return rpaint;
}
